package com.itheima.ssm.service.impl;

import com.itheima.ssm.dao.IUserDao;
import com.itheima.ssm.domain.Role;
import com.itheima.ssm.domain.UserInfo;
import com.itheima.ssm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service("userService")
@Transactional
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserDao iUserDao;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        实现查询数据库的用户名的操作，返回的一个userInfo
        UserInfo userInfo = null;
        try {
            userInfo = iUserDao.findByUsername(username);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        因为上面是要返回的一个UserDetails，所以调用他的子类User进行返回
//        User返回是要带三个参数
//        User user = new User(userInfo.getUsername(),"{noop}"+userInfo.getPassword(),getAuthority(userInfo.getRoles()));
        User user = new User(userInfo.getUsername(),userInfo.getPassword(),userInfo.getStatus()==0 ? false:true,true,true,true,getAuthority(userInfo.getRoles()));
        return user;
    }

//    返回的用户的权限
    public List<SimpleGrantedAuthority> getAuthority(List<Role> roles){
        List<SimpleGrantedAuthority> list = new ArrayList <>();
        for(Role role : roles){
            list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        }
        return list;
    }

    @Override
    public List <UserInfo> findAll() throws Exception {
        return iUserDao.findAll();
    }

    @Override
    public void save(UserInfo info) throws Exception{
//        密码加密处理
        info.setPassword(bCryptPasswordEncoder.encode(info.getPassword()));
        iUserDao.save(info);
    }

    @Override
    public UserInfo findById(int id) throws Exception {
        return iUserDao.findById(id);
    }

    @Override
    public List <Role> findOtherRoles(int id) throws Exception {
        return iUserDao.findOtherRoles(id);
    }

    @Override
    public void addRoleToUser(int userId, int[] roleIds) throws Exception {
        for (int roleId : roleIds){
            iUserDao.addRoleToUser(userId,roleId);
        }
    }
}
